<?php

namespace App\Http\Controllers\Admin;

use App\Http\Resources\CommonCollection;
use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;

class OrdersController extends AdminController
{
    public function __construct()
    {
        parent::__construct();
        $this->middleware('auth:api');
    }

    public function ordersList(Request $request, Order $model)
    {
        $per_page = $request->get('per_page', 10);

        $search_data = json_decode($request->get('search_data'), true);

        $keyword = isset_and_not_empty($search_data, 'keyword');
        if ($keyword) {
            $userIds = User::where("phone", "like", "%{$keyword}%")->pluck("id");
            $model = $model->whereIn('user_id', $userIds)->orWhere("no", 'like', "%{$keyword}%");
        }

        $pay_at = date_isset_and_not_empty($search_data, 'pay_at');
        if ($pay_at) {
            $model = $model->columnBetween('paid_at', $pay_at);
        }

        $type = isset_and_not_empty($search_data, 'type');
        if ($type) {
            $model = $model->where("type", $type);
        }

        $status = isset_and_not_empty($search_data, 'status');
        if ($status) {
            if($status == 1){
                $model = $model->whereNull("paid_at")->where('bespeak', 0);
            }
            if($status == 2){
                $model = $model->whereNull("paid_at")->where('bespeak', 1);
            }
            if($status == 3){
                $model = $model->whereNotNull("paid_at");
            }
        }

        $order_by = isset_and_not_empty($search_data, 'order_by');
        if ($order_by) {
            $order_by = explode(',', $order_by);
            $model = $model->orderBy($order_by[0], $order_by[1]);
        }

        return new CommonCollection($model->with(['items', 'user'])->paginate($per_page));
    }
}
